import { createDraw } from '../../../../../utils/createDraw'
import * as turf from '@turf/turf'

export const measureLength = ($map) => {
    //画笔图层
    const source = new ol.source.Vector({})
    const layer = new ol.layer.Vector({
        source,
        title:"长度画笔"
    })
    $map.addLayer(layer)
    //创建画笔
    const draw = createDraw({
        type: "LineString",
        source
    })
    $map.addInteraction(draw)
    
    draw.on('drawend', (evt) => {
        //获取坐标
        const position = evt.feature.getGeometry().getCoordinates()
        //计算长度
        var line = turf.lineString(position);
        var length = turf.length(line, { units: 'kilometers' }).toFixed(2);

        //计算中心点
        let features = {
            type: "FeatureCollection",
            features: [],
        }
        position.forEach(item => {
            const feature = {
                type: "Feature",
                geometry: {
                    type: "Point",
                    coordinates: item
                }
            }
            features.features.push(feature)
        })
        var center = turf.center(features);

        //添加标注
        const markerSource = new ol.source.Vector({
            features: new ol.format.GeoJSON().readFeatures({
                type: "FeatureCollection",
                features: [center]
            })
        })
        const markerLayer = new ol.layer.Vector({
            source: markerSource,
            style: new ol.style.Style({
                text: new ol.style.Text({
                    offsetX: 0,
                    offsetY: 10,
                    font: 'normal 14px 微软雅黑',
                    text: `${length} 千米`,
                    fill: new ol.style.Fill({ color: '#333' }),
                    stroke: new ol.style.Stroke({ color: "#0000ff", width: 2 })
                })
            }),
            title:"长度标注"
        })
        $map.addLayer(markerLayer)
    })

    return { draw }
}